package com.lw.leetcode.arr.c;

/**
 * Created with IntelliJ IDEA.
 * 面试题 17.06. 2出现的次数
 *
 * @author liw
 * @version 1.0
 * @date 2023/1/12 12:16
 */
public class NumberOf2sInRange {


    public static void main(String[] args) {
        NumberOf2sInRange test = new NumberOf2sInRange();


        // 279
//        int n = 888;

        // 1
        int n = 3;

        int i = test.numberOf2sInRange(n);
        System.out.println(i);

    }

    public int numberOf2sInRange(int n) {
        int sum = 0;
        int[] items = new int[10];
        int item = 1;
        int[] arr2 = new int[10];
        arr2[0] = 1;
        for (int i = 1; i < 10; i++) {
            items[i] = i * item;
            item *= 10;
            arr2[i] = item;
        }
        int[] arr = new int[10];
        int t = n;
        int index = 0;
        while (t != 0) {
            arr[index++] = t % 10;
            t /= 10;
        }
        item = 0;
        for (int i = index - 1; i >= 0; i--) {
            int c = arr[i];
            item += c * arr2[i];
            if (c < 2) {
                sum += items[i] * c;
            } else if (c == 2) {
                sum += items[i] * c + (n - item + 1);
            } else {
                sum += items[i] * c + arr2[i];
            }
        }
        return sum;
    }


}
